//ajax
export function ajax(url, type = "get", data = null) {
  return new Promise((res, rej) => {
    fetch(url, {
      method: type,
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: !data ? null : JSON.stringify(data),
    })
      .then((Response) => Response.json())
      .then((json) => res(json))
      .catch((err) => rej(err));
  });
}
//timeout
export function timeout(t) {
  return new Promise((success) => {
    setTimeout(() => {
      success();
    }, t);
  });
}
/*
获取某url中的某参数值
调用:GetUrlQueryString("[url地址]","[参数名]");
*/
export function GetUrlQueryString(url, name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = url.substring(url.indexOf("?")).substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}
//将url参数转为json对象
export function parseQueryString(str) {
  var arr = [],
    length = 0,
    res = {},
    si = str.indexOf("?");
  str = str.substring(si + 1);
  arr = str.split("&");
  length = arr.length;
  for (var i = 0; i < length - 1; i++) {
    res[arr[i].split("=")[0]] = arr[i].split("=")[1];
  }
  return res;
}

//取chrome储存
export async function getChromeStorage(_name) {
  return new Promise((resolve) => {
    chrome.storage.local.get(_name, (res) => {
      resolve(res[_name]);
    });
  })
}

//设置chrome储存
export async function setChromeStorage(keyValue) {
  return new Promise((resolve) => {
    chrome.storage.local.set(keyValue, () => {
      resolve(true)
    });
  })
}